#!/usr/bin/env python
#Copyright (c) 2011 Isaac Dawson (WBTS Project)
#Permission is hereby granted, free of charge, to any person obtaining a copy 
#of this software and associated documentation files (the "Software"), to deal 
#in the Software without restriction, including without limitation the rights 
#to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
#copies of the Software, and to permit persons to whom the Software is furnished
#to do so, subject to the following conditions:
#
#The above copyright notice and this permission notice shall be included in all
#copies or substantial portions of the Software.
#
#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
#IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
#FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
#AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
#LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
#OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
#THE SOFTWARE.

from twisted.application import service, internet
from twisted.internet import reactor, defer
from twisted.python import components, log
from twisted.web import resource, server, static, xmlrpc
from twisted.names import dns, resolve
from zope.interface import Interface, implements

from wbts.utils import mgmt_utils
from wbts.storage import *
from wbts.resc.db_resources import DownloadJsDbResults

class IWBTSMgmtService(Interface):
    def getSettingCfgValues(self, setting_name):
        """
        Returns a deferred of a dictionary object of the services settings.
        """
        return
    
    def getSettingCfgValue(self, setting_name, value_name):
        """
        returns a deferred of the value (object type depends on value_name).
        """
        return
    
    def checkSettingCfgValue(self, setting_name, value_name, value, value_type):
        """
        returns a deferred of true/false whether the value is OK.
        """
        return
  
    def updateSettingCfgValue(self, setting_name, name, value, type=None):
        """
        returns a deferred of true/false whether the value was updated or not.
        """
        return
    
    def delSettingCfgValue(self, setting_name, name):
        """
        returns a deferred of true/false for whether the value could be deleted.
        Some values are not allowed to be deleted.
        """
        return
    
    def checkValueType(self, value, value_type):
        """
        returns a deferred of true/false depending on whether or not value is
        a valid value.
        """
        return    
    
class WBTSMgmtService(service.Service):
    implements(IWBTSMgmtService)
    mMgmtTree = None # this will be set by our mgmt tree so we can add resources
    def __init__(self, config, multiService):
        self.mConfig = config
        self.mWbtsService = multiService
        self.mDnsService = None
        self.mVhostService = None
        self.mValidDbs = []
        self.mRpcServices = []
        self.mDefaultTables = ["test_results", 
                               "pretest_results", 
                               "request_logger"]
        self._getDbSettings()
        
    def _getDbSettings(self):
        """
        connects to our database.
        """
        d = self.getSettingCfgValues('DBClientSettings')
        d.addCallback(self._cb_getDbSettings)
        d.addErrback(lambda err: err)
        return 
    
    def _cb_getDbSettings(self, db_settings):
        db_name = db_settings['db_name']
        db_class = db_settings['db_class']
        db_connectstring = db_settings['db_connectstring']
        self.mValidDbs.append(db_name)
        # How's that old saying go?
        # If you're using eval, You're Probably Doing It Wrong.
        self.mDbConn = eval("%s(\"%s\")"%(db_class,db_connectstring))
        d = self.mDbConn.connect()
        def addTables(result):
            for table in self.mDefaultTables:
                d = self.mDbConn.createTable(table)
                d.addCallback(self._cb_tableCreate, table)
                d.addErrback(lambda err: err)
            return
        
        def dbConnectError(result):
            print "Error connecting to database: %s"%result
            return

        d.addCallback(addTables)
        d.addErrback(dbConnectError)
        return d
    
    def _cb_tableCreate(self, result, table_name):
        # at this point logging has not started, just use print.
        if (result == 1):
            print "[DB] Table %s already existed."%table_name
        else:
            print "[DB] Table %s was created successfully."%table_name
        return
    
    def getSettingCfgValues(self, setting_name):
        """
        Returns a deferred of a dictionary object of the services settings.
        """
        return defer.succeed(self.mConfig.getCfgSectionValues(setting_name))
    
    def getSettingCfgValue(self, setting_name, value_name):
        """
        returns a deferred of the value (object type depends on value_name).
        """
        return defer.succeed(self.mConfig.getCfgValue(setting_name, value_name))
    
    def checkSettingCfgValue(self, setting_name, value_name, value, value_type):
        """
        returns a deferred of true/false whether the value is OK.
        """
        return defer.succeed(self.mConfig._checkCfgValue(setting_name,
                                                         value_name,
                                                         value,
                                                         value_type))
    
    def updateSettingCfgValue(self, setting_name, name, value, type=None):
        """
        returns a deferred of true/false whether the value was updated or not.
        """
        return defer.succeed(self.mConfig.addCfgValue(setting_name,
                                                      value_name,
                                                      value,
                                                      value_type))
    
    def delSettingCfgValue(self, setting_name, name):
        """
        returns a deferred of true/false for whether the value could be deleted.
        Some values are not allowed to be deleted.
        """
        return defer.succeed(self.mConfig.delCfgValue(setting_name, name))
        
    def checkValueType(self, value, value_type):
        """
        returns a deferred of true/false depending on whether or not value is
        a valid value.
        """
        return defer.succeed(self.mConfig.checkValue(value, value_type))

    def addServiceXRResources(self, service, xmlrpc_resources, resource_name):
        self.mRpcServices.append(resource_name)
        self.mMgmtTree.putChild(resource_name, xmlrpc_resources(service))
        return

class WBTSMgmtXR(xmlrpc.XMLRPC):
    isLeaf = True

    def __init__(self, service):
        xmlrpc.XMLRPC.__init__(self, allowNone=True)
        self.mService = service
        self.putSubHandler('system', xmlrpc.XMLRPCIntrospection(self))

    def xmlrpc_getSettingCfgValues(self, setting_name):
        return self.mService.getSettingCfgValues(setting_name)
    
    def xmlrpc_getSettingCfgValue(self, setting_name, value_name):
        return self.mService.getSettingCfgValue(setting_name, value_name)
        
    def xmlrpc_checkSettingCfgValue(self, setting_name, value_name, value,
                                    value_type):
        return self.mService.checkSettingCfgValue(setting_name, value_name,
                                                  value, value_type)
        
    def xmlrpc_updateSettingCfgValue(self, setting_name, value_name, value,
                                     value_type):
        return self.mService.updateSettingCfgValue(setting_name, value_name,
                                                   value, value_type)
    
    def xmlrpc_delSettingCfgValue(self, setting_name, name):
        return self.mService.delSettingCfgValue(setting_name, name)

    def xmlrpc_checkValueType(self, value, value_type):
        return self.mService.checkValueType(value, value_type)
        
    def xmlrpc_listRpcServices(self):
        return self.mService.mRpcServices

class WBTSStorageXR(xmlrpc.XMLRPC):
    def __init__(self, service):
        xmlrpc.XMLRPC.__init__(self, allowNone=True)
        self.mService = service
        self.mDb = self.mService.mDbConn
        self.putSubHandler('system', xmlrpc.XMLRPCIntrospection(self))
    
    def _cb_error(self, msg):
        return {"error": str(msg)}
    
    def _cb_clean_results(self, results):
        """
        Serialized the _id into a string value.
        """
        if isinstance(results, list):
            for result in results:
                if ("_id" in result.keys()):
                    result["_id"] = str(result["_id"])
        elif isinstance(results, dict):
            if ("_id" in results.keys()):
                results["_id"] = str(results["_id"])
        return results
    
    def xmlrpc_get_type(self):
        return self.mDb.mDbType
    
    def xmlrpc_find_one(self, db_name, search_key=None):
        data = self.mDb[db_name].find_one(search_key)
        data.addCallback(self._cb_clean_results)
        data.addErrback(self._cb_error)
        return data
    
    def xmlrpc_find(self, db_name, skip=0, limit=-1, search_key=None):
        """
        Call to db.find is (search, skip, limit) but due to None types and
        XML-RPC had to move search_key to last argument.
        """
        data = self.mDb[db_name].find(search_key, skip, limit)
        data.addCallback(self._cb_clean_results)
        data.addErrback(self._cb_error)
        return data
    
    def xmlrpc_count(self, db_name):
        data = self.mDb[db_name].count()
        data.addCallback(lambda ret: ret) # just returns the count value
        data.addErrback(self._cb_error)
        return data
        
    def xmlrpc_insert(self, db_name, record):
        return self.mDb[db_name].insert(record)
    
    def xmlrpc_remove(self, db_name, search_key=None):
        return self.mDb[db_name].remove(search_key)
    
    def xmlrpc_drop(self, db_name):
        return self.mDb.dropTable(db_name)
    
    def xmlrpc_save(self):
        """
    Only for WBTSPydictDB's, saves the results to disk.
        """
        return self.mDb._save()


class WBTSMgmtTree(resource.Resource):
    implements(resource.IResource)
    def __init__(self, service):
        resource.Resource.__init__(self)
        self.mService = service
        self.mService.mMgmtTree = self # add a reference to our main service.
        def cb_putChildren(path):
            self.mRoot = path
            self.putChild('console', static.File(self.mRoot))
            self.putChild('mgmtrpc', WBTSMgmtXR(self.mService))
            # see resc.db_resources
            self.putChild('download', DownloadJsDbResults(self.mService))
            
        d = self.mService.getSettingCfgValue('ManagementSettings', 'mgmt_root')
        d.addCallback(cb_putChildren)
        d.addErrback(mgmt_utils.cb_print_error)
        

    def render_GET(self, request):
        request.redirect('console/')
        request.finish()
        return server.NOT_DONE_YET
    
    def getChild(self, path, request):
        if path=="":
            return self
        return resource.Resource.getChild(self, path, request)
        
components.registerAdapter(WBTSMgmtTree, IWBTSMgmtService, resource.IResource)